import os
import uuid
import numpy as np


def allowed_file(filename, allowed_extensions):
    """检查文件扩展名是否允许上传"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions


def unique_filename(filename):
    """为上传文件生成唯一文件名"""
    name, ext = os.path.splitext(filename)
    return name + '_' + str(uuid.uuid4())[:8] + ext


def convert_numpy_types(obj):
    """递归将NumPy类型转换为Python原生类型"""
    if isinstance(obj, np.integer):
        return int(obj)
    elif isinstance(obj, np.floating):
        return float(obj)
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    elif isinstance(obj, np.bool_):
        return bool(obj)
    elif isinstance(obj, dict):
        return {k: convert_numpy_types(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_numpy_types(i) for i in obj]
    else:
        return obj
